import { DeviceEventEmitter } from "react-native";
import AlarmStrategyManager from "../libs/Alarm";
import XLog from "../libs/XLog";
import CommunicationManager from "./CommunicationManager";
import DataCenter from "./DataCenter";
import { ACK_Type, Adjust_Model, Control_Level, Topic_Control } from "./LogicConstant";
import SerialPortManager from "./SerialPortManager";
import { formatterSendTopic } from "./TopicUtil";
import { commonMakeGateBrightControlCmd, commonMakeControlRequest, queryStrategyBrightness } from "./Utils";

export default class StrategyManager {
    static strategyTimer = null;

    static installStrategyLogic() {
        this.strategyTimer = setInterval(()=>{
            try{
                let control_cmd = [];
                for(let loop of (DataCenter.getLocalCabinetData().loop)||[]) {
                    if(loop.loopStrategyId) {
                        let strategy = DataCenter.queryStrategyById(loop.loopStrategyId);
                        let brightness = queryStrategyBrightness(strategy?.setting);
                        if(brightness) {
                            if(loop.loopCurrentValue != brightness) {
                                SerialPortManager.controlLight(loop.loopNumber, brightness);
                                SerialPortManager.controlLightEnd();
                                control_cmd.push(commonMakeGateBrightControlCmd(loop.loopNumber, brightness));
                                DataCenter.setColonyCabinetDeviceLight(DataCenter.gateId, [loop.loopNumber], brightness, false);
                            }
                        } else {
                            XLog.e("StrategyManager queryStrategyById failed:", loop.loopStrategyId);
                        }
                    }
                }
                if(control_cmd.length > 0) {
                    DeviceEventEmitter.emit("localCabinet");
                    DeviceEventEmitter.emit("tunnelCabinet");
                    CommunicationManager.send2Master(formatterSendTopic(Topic_Control),
                        commonMakeControlRequest(
                            Control_Level.LEVEL_STRATEGY,
                            true,
                            0,
                            DataCenter.gateId,
                            Adjust_Model.ADJUST_DIRECT_LIGHT,
                            0,control_cmd, false));
                }
            }catch(error) {
                XLog.e("installStrategyLogic exception:", error?.message);
            }
        }, 1000 * 60);
    }

    static uninstallStrategyLogic() {
        if(this.strategyTimer) {
            clearInterval(this.strategyTimer);
            this.strategyTimer = null;
        }
    }
}